#include "RemoteControlRadio.h"

radiopacket_t packet;
/*
* Radio		Seeeduino
*  Vcc				48
*   CE				49
*  CSN				47
*  SCK				52
* MOSI				51
* MISO				50
*  IRQ				2
*  GND				GND
*/

void setupRadioTransmitter()
{
	//hard coding the address for now and will make improvements later
	//uint8_t rx_addr[RADIO_ADDRESS_LENGTH] = { 0x98, 0x76, 0x54, 0x32, 0x10 };//debug station
	uint8_t rx_addr[RADIO_ADDRESS_LENGTH] = { 0x01, 0x02, 0x03, 0x04, 0x05 };//remote joystick address
	uint8_t tx_addr[RADIO_ADDRESS_LENGTH] = { 0x05, 0x04, 0x03, 0x02, 0x01 };//hovercraft address

	pinMode( 48, OUTPUT );
	digitalWrite( 48, HIGH );

	//delay( RADIO_WARMUP );
	Serial.println( "turned Radio power on" );
	// initializing radio
	Serial.println( "Initializing Radio..." );
	Radio_Init();
	Serial.println( "Radio Initialized" );

	// configure radio
	Serial.println( "Configuring Radio..." );
	Radio_Configure_Rx(RADIO_PIPE_0, rx_addr, ENABLE);
	Radio_Configure(RADIO_2MBPS, RADIO_HIGHEST_POWER);
	Serial.println( "Radio Configured" );

	// set transmit to address
	Serial.println( "Setting tx address..." );
	Radio_Set_Tx_Addr( tx_addr );
	Serial.println( "tx address set" );

	// setup packet
	Serial.println( "Setting up packet..." );
	packet.type = MESSAGE;
	memcpy(packet.payload.message.address, rx_addr, RADIO_ADDRESS_LENGTH);
	Serial.println( "Packet Setup" );
}

void sendCommand( int command )
{
	packet.payload.message.messageid = command;
	snprintf((char*)packet.payload.message.messagecontent, 20, "see id for command");
	Radio_Transmit(&packet, RADIO_WAIT_FOR_TX);
	delay( 20 );
}

void radio_rxhandler(uint8_t pipe_number)
{
	Serial.begin( BAUD_RATE );
	// Receive the message
	Radio_Receive( &packet );

	if( packet.type == MESSAGE )
	{
		Serial.println( "Radio signal received" );
		Serial.print( "Message Type: " );
		Serial.println( packet.payload.message.messageid );
		Serial.print( "value:" );
		Serial.println( (char*)packet.payload.message.messagecontent );
	}

	if( packet.type == READING )
	{
		Serial.print( "Sonar Reading received: " );
		if( packet.payload.reading.messageid == SONAR_READING )
		{
			Serial.print( "Sonar Reading received: " );
			Serial.println( packet.payload.reading.value );
		}
		else
		{
			Serial.println( "non Sonar reading" );
		}
	}
	else
	{
		Serial.print( "Received non-MESSAGE packet type" );
	}
}
